<?php

namespace common\models;

use backend\controllers\BaseController;
use common\cache\DictCache;
use common\helpers\commonApi;
use common\helpers\PageApi;
use Yii;
use yii\helpers\ArrayHelper;

/**
 * This is the model class for table "{{%withdrawal}}".
 *
 * @property int $id
 * @property int|null $userid 用户id
 * @property int|null $fund_type 资金类型
 * @property float|null $amount 提现金额
 * @property int|null $way 提现方式
 * @property int|null $review_status 审核状态
 * @property string|null $review_time 审核时间
 * @property string|null $review_remarks 审核备注
 * @property string|null $create_time 申请时间
 * @property string|null $update_time 修改时间
 * @property string|null $callback_info 回调信息
 * @property string|null $collection_info 收款信息
 * @property string|null $orderid 订单号
 * @property string|null $fee 手续费
 * @property int|null $campus_id 校区id
 */
class Withdrawal extends BaseModel
{
    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return '{{%withdrawal}}';
    }

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['userid', 'fund_type', 'way', 'review_status','campus_id'], 'integer'],
            [['amount','fee'], 'number'],
            [['review_time', 'create_time', 'update_time'], 'safe'],
            [['review_remarks', 'callback_info','collection_info','orderid'], 'string'],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'userid' => '用户id',
            'fund_type' => '资金类型',
            'amount' => '提现金额',
            'way' => '提现方式',
            'review_status' => '审核状态',
            'review_time' => '审核时间',
            'review_remarks' => '审核备注',
            'create_time' => '申请时间',
            'update_time' => '修改时间',
            'callback_info' => '回调信息',
            'collection_info' => '收款信息',
            'orderid' => '订单号',
            'fee' => '手续费',
            'campus_id' => '校区id',
        ];
    }

    /**
     * 生成订单号
     * @return string
     */
    public static function makeOrderid()
    {
        $orderId = date('YmdHis').rand(1000, 9999);
        if (self::find()->where(['orderid' => $orderId])->exists()) {
            $orderId = self::makeOrderid();
        }
        return $orderId;
    }
    /**
     * 申请提现
     * @param $userid
     * @param $post
     * @return array|mixed
     */
    public function apply($userid,$post)
    {
        if (empty($post['amount'])){
            return commonApi::message('请输入提现金额',false);
        }
        if (!is_numeric($post['amount'])){
            return commonApi::message('提现金额错误');
        }
        if ($post['amount']<=0){
            return commonApi::message('提现金额必须大于0',false);
        }
        $sys = System::getModel()->toArray();
        $min_withdraw = $sys['min_withdraw']??0;
        if ($min_withdraw>0){
            if ($post['amount']<$min_withdraw){
                return commonApi::message('提现金额不小于'.$min_withdraw,false);
            }
        }
        $fund_type = DictCache::get('fund_type');
        if (empty($fund_type[$post['fund_type']])){
            return commonApi::message('参数错误',false);
        }
        $withdraw_way = DictCache::get('withdraw_way');
        if (empty($withdraw_way[$post['way']])){
            return commonApi::message('打款方式不正确',false);
        }
        $collection_info = '';
        if ($post['way']==1){
            $coll = CollectionInfo::find()->where(['userid'=>$userid])->asArray()->one();
            if (!$coll){
                return commonApi::message('请完善收款信息',false);
            }
            $collection_info = json_encode($coll);
        }
        $fee = 0;
        if ($post['fund_type']==1){
            $fee = $sys['run_withdraw_fee'];
        }
        if ($post['fund_type']==2){
            $fee = $sys['dis_withdraw_fee'];
        }
        if ($post['fund_type']==3){
            $fee = $sys['ca_withdraw_fee'];
        }
        $feeAmount = 0;
        if ($fee>0){
            $feeAmount = $post['amount']*$fee/100;
        }
        $orderid = self::makeOrderid();
        $model = new self();
        $model->userid = $userid;
        $model->fund_type = $post['fund_type'];
        $model->amount = $post['amount'];
        $model->way = $post['way'];
        $model->review_status = 0;
        $model->collection_info = $collection_info;
        $model->orderid = "$orderid";
        $model->fee = $feeAmount;
        $model->campus_id = $post['campus_id_id']??'';
        if ($model->save()){
            $use = $fund_type[$post['fund_type']]."提现，记录id【{$model->id}】";
            $result = (new User())->operBrokerage($userid,$model->fund_type,2,$model->amount,$use);
            if (!$result['success']){
                self::deleteAll(['id'=>$model->id]);
                return $result;
            }
            return commonApi::message('申请成功，等待审核');
        }
        return commonApi::message(commonApi::getModelError($model),false);
    }

    /**
     * 提现列表
     * @param $userid
     * @param $where
     * @param $page
     * @return array
     */
    public function getList($userid,$where,$page)
    {
        $query = self::find()
            ->select(['id as w_id','fund_type','amount','way','review_status','create_time','review_remarks','fee'])
            ->where(['userid'=>$userid])
            ->andWhere($where)
            ->orderBy(['create_time'=>SORT_DESC]);
        $data = PageApi::apiPage($query,$page);
        $review_status = DictCache::get('review_status');
        $withdraw_way = DictCache::get('withdraw_way');
        foreach ($data['data'] as &$datum){
            $datum['review_status_title'] = $review_status[$datum['review_status']]??'';
            $datum['review_remarks'] = $datum['review_remarks']??'';
            $datum['way_title'] = $withdraw_way[$datum['way']]??'';
        }
        return commonApi::message('ok',true,$data);
    }




}
